package alex.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 测试#{@link java.nio.channels.FileChannel} usage.
 *
 * @author alex.shu
 */
public class FileChannelDemo1 {

    private String path = this.getClass().getClassLoader().getResource("./nio/FileChannel1.txt").getPath();

    public static void main(String[] args) throws Exception {
        new FileChannelDemo1().writeToFile();
        new FileChannelDemo1().readFromFile();
    }

    private void writeToFile() throws IOException {

        FileOutputStream fos = new FileOutputStream(new File(path));
        FileChannel fileChannel = fos.getChannel();

        try {
            String str = "abcde";

            ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
            System.out.println(String.format("A position: %s ", buffer.position()));

            System.out.println("write() 1 返回值：" + fileChannel.write(buffer));

            System.out.println(String.format("B position: %s ", buffer.position()));

            fileChannel.position(2);
            buffer.rewind(); // 还原buffer的position = 0;

            System.out.println("write() 2 返回值：" + fileChannel.write(buffer));

            System.out.println(String.format("C position: %s ", buffer.position()));
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileChannel.close();
        fos.close();
    }

    private void readFromFile() throws IOException {
        FileInputStream fis = new FileInputStream(new File(path));
        FileChannel fileChannel = fis.getChannel();

        try {
            ByteBuffer buffer = ByteBuffer.allocate(10);
            System.out.println(String.format("A position: %s ", buffer.position()));

            int readSize = fileChannel.read(buffer);
            System.out.println("read() 1 返回值：" + readSize);
            System.out.println("read capacity：" + buffer.capacity());
            System.out.println("read limit：" + buffer.limit());

            byte[] data = new byte[15];
            System.out.println("read data：" + buffer.get(data));
        } catch (IOException e) {
            e.printStackTrace();
        }

        fileChannel.close();
        fis.close();
    }
}
